//
//  AppDelegate.m
//  wedding
//
//  Created by 常宽 on 15/1/14.
//  Copyright (c) 2015年 常宽. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeViewController.h"
#import "PreparaViewController.h"
#import "SetUpViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    HomeViewController *homeController = [[HomeViewController alloc]init];
    UINavigationController *homeNav = [[UINavigationController alloc] initWithRootViewController:homeController];
    homeController.title = @"我其实是首页";
    UIImage *hP0 = [[UIImage imageNamed:@"首页20.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *hP1 = [[UIImage imageNamed:@"首页.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    homeNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image:hP0 selectedImage:hP1];
    
    PreparaViewController *preparController = [[PreparaViewController alloc]init];
    UINavigationController *preparNav = [[UINavigationController alloc]initWithRootViewController:preparController];
    preparController.title = @"能为您做些什么";
    UIImage *pC0 = [[UIImage imageNamed:@"筹备20.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *pC1 = [[UIImage imageNamed:@"筹备.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    preparNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"筹备" image:pC0 selectedImage:pC1];
    
    SetUpViewController *settingController = [[SetUpViewController alloc] init];
    UINavigationController *settingNav = [[UINavigationController alloc]initWithRootViewController:settingController];
    settingController.title = @"您的需求都在这";
    UIImage *sU0 = [[UIImage imageNamed:@"设置20.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *sU1 = [[UIImage imageNamed:@"设置.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    settingNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"设置" image:sU0 selectedImage:sU1];
    
    
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    tabBarController.viewControllers = @[homeNav, preparNav, settingNav];
    [_window setRootViewController:tabBarController];
    
    /// 改变tabBar上的字体颜色
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[WebColor crimson], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [self saveContext];
}

#pragma mark 添加coreData
#pragma mark - Core Data stack coreData栈,以下就是coredata的

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
/// 获取文件路径
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
/// 被管理数据模型类getter方法 懒加载
- (NSManagedObjectModel *)managedObjectModel {
    // 判断 managedObjectModel 是否为空,不是返回,是空创建
    if (_managedObjectModel != nil) {
        // 不是空 返回
        return _managedObjectModel;
    }
    // 是空 创建
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"wedding" withExtension:@"momd"];
    // 利用modelURL路径,创建managedObjectModel类
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

/// getter方法中调用
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // 创建连接器 ,初始化时需要 被管理对象模型managedObjectModel
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
    // 连接器 1, 需要存储路径
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Wedding.sqlite"]; // sqlite类型
    // 2, 还需要被管理对象模型 ManagedObjectModel;
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    
    // 给链接器persistentStoreCoordinator 添加存储路径,还要添加设置, 添加选...
    // 字典的两个option升级coreData用的
    /*
     * 自动合并
     * 自动寻址
     */
    NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@(YES), NSInferMappingModelAutomaticallyOption:@(YES)};
    /*
     * 参数1 存储类型NSSQLiteStoreType,NSInMemoryStoreType,NSBinaryStoreType
     * 参数2 设置
     * 参数3 路径       //
     * 参数4 options   //上面的字典
     */
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

/// 数据管理器类getter方法
- (NSManagedObjectContext *)managedObjectContext {
    // 同样,判断是否为空
    if (_managedObjectContext != nil) {
        // 不是空,返回
        return _managedObjectContext;
    }
    // 是空 创建
    // 创建一个管理器类 必须设置,coordinator 连接器类
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    // 当前的连接器类是否为空
    if (!coordinator) {
        return nil;
    }
    // 连接器不为空才创建 管理器类context;
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support
///  保存数据的命令
- (void)saveContext {
    // 获得管理器类
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    
    if (managedObjectContext != nil) {
        NSError *error = nil;
        
        // 盘点数据内容是否为空 && [contextsave:&error]
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


@end
